/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package daemonClient;

import java.rmi.UnexpectedException;
import java.util.Random;

public class Vernam
{
	private String phrase = "";
	private String key = "";

	public byte[] XOR() throws UnexpectedException
	{
		if (phrase == "" || key == "")
			throw new UnexpectedException("Phrase or key are empty.");

		byte[] phrase = this.phrase.getBytes();
		byte[] key = this.key.getBytes();
		byte[] result = new byte[phrase.length];
		int n = 0;

		for (int i = 0; i < phrase.length; i++)
		{
			byte a = phrase[i];
			byte b = key[n];
			result[i] = (byte) (a ^ b); // XOR
			n++;
			if (n >= key.length)
				n = 0;
		}

		return result;
	}

	public void generateKey()
	{
		int length = phrase.length();
		
		final byte[] temp = new byte[length];
		Random rnd = new Random();

		for (int i = 0; i < length; i++)
		{
			temp[i] = (byte) (rnd.nextInt(256));
		}
		
		key = new String(temp);
	}

	public void setPhrase(String Phrase)
	{
		phrase = Phrase;
	}

	public void forget()
	{
		key = "";
		phrase = "";
	}
}
